const axios = require('axios');

// 模拟点赞操作并检查UI状态
async function testLikeUI() {
  const userId = 'user1';
  const dynamicId = 'd1';

  try {
    console.log('🧪 开始测试点赞UI状态变化...\n');
    
    // 1. 获取初始状态
    console.log('📋 步骤1: 获取初始动态列表');
    const initialResponse = await axios.get(`http://localhost:3000/api/dynamic/list/${userId}`);
    const initialDynamic = initialResponse.data.data.find(d => d.id === dynamicId);
    console.log(`初始状态 - 动态ID: ${dynamicId}, 点赞数: ${initialDynamic.like_count}, 已点赞: ${initialDynamic.is_liked}\n`);
    
    // 2. 执行点赞操作
    console.log('👍 步骤2: 执行点赞操作');
    const likeResponse = await axios.post('http://localhost:3000/api/dynamic/like', {
      userId: userId,
      dynamicId: dynamicId
    });
    console.log('点赞响应:', likeResponse.data);
    
    // 3. 获取点赞后的状态
    console.log('\n📋 步骤3: 获取点赞后的动态列表');
    const afterLikeResponse = await axios.get(`http://localhost:3000/api/dynamic/list/${userId}`);
    const afterLikeDynamic = afterLikeResponse.data.data.find(d => d.id === dynamicId);
    console.log(`点赞后状态 - 动态ID: ${dynamicId}, 点赞数: ${afterLikeDynamic.like_count}, 已点赞: ${afterLikeDynamic.is_liked}\n`);
    
    // 4. 再次点赞（取消点赞）
    console.log('👍 步骤4: 再次点赞（取消点赞）');
    const unlikeResponse = await axios.post('http://localhost:3000/api/dynamic/like', {
      userId: userId,
      dynamicId: dynamicId
    });
    console.log('取消点赞响应:', unlikeResponse.data);
    
    // 5. 获取最终状态
    console.log('\n📋 步骤5: 获取最终动态列表');
    const finalResponse = await axios.get(`http://localhost:3000/api/dynamic/list/${userId}`);
    const finalDynamic = finalResponse.data.data.find(d => d.id === dynamicId);
    console.log(`最终状态 - 动态ID: ${dynamicId}, 点赞数: ${finalDynamic.like_count}, 已点赞: ${finalDynamic.is_liked}\n`);
    
    // 6. 验证状态变化
    console.log('✅ 验证结果:');
    console.log(`- 初始点赞数: ${initialDynamic.like_count}, 最终点赞数: ${finalDynamic.like_count}`);
    console.log(`- 点赞数变化: ${finalDynamic.like_count - initialDynamic.like_count}`);
    console.log(`- 初始已点赞: ${initialDynamic.is_liked}, 最终已点赞: ${finalDynamic.is_liked}`);
    
    if (finalDynamic.like_count === initialDynamic.like_count && finalDynamic.is_liked === initialDynamic.is_liked) {
      console.log('✅ 测试通过：点赞状态正确恢复');
    } else {
      console.log('❌ 测试失败：点赞状态异常');
    }
    
  } catch (error) {
    console.error('❌ 测试出错:', error.response?.data || error.message);
  }
}

// 运行测试
async function runTest() {
  console.log('🚀 开始运行点赞UI状态测试...\n');
  
  await testLikeUI();
  
  console.log('\n🏁 测试完成！');
}

// 如果直接运行此脚本
if (require.main === module) {
  runTest();
}

module.exports = { testLikeUI }; 